import { Chunks, UpdateFolderId } from './../types/file'
import { request } from '~/util'
import { FileInfo } from '~/types'
import { AddFolder, ChunkInfo, FileUpload, fileInfo } from '~/types/file'

export const getFile = (folderData: FileInfo) => {
  return request.get<{ list: fileInfo[]; totalSize: number }>(`/files/`, {
    params: folderData
  })
}
export const uploadsFile = (fileInfo: FileUpload) => {
  const formData = new FormData()
  formData.append('userId', fileInfo.userId.toString())
  formData.append('folderId', fileInfo.folderId.toString())
  formData.append('originalName', fileInfo!.file.name) // 原始文件名
  formData.append('fileId', fileInfo.fileId!.toString())
  // 如果存在分片信息，则为分片上传，否则为普通上传
  if (fileInfo.chunk && fileInfo.index !== undefined && fileInfo.totalChunks) {
    // 分片上传
    formData.append('index', fileInfo.index.toString())
    formData.append('totalChunks', fileInfo.totalChunks.toString())
    formData.append('chunk', fileInfo.chunk)
  } else {
    // 普通上传
    formData.append('file', fileInfo.file)
  }

  console.log('🚀 ~ uploadsFile ~ formData:', formData)
  return request.post(`/files/upload`, formData)
}
// 检查分片
export const checkChunks = (chunks: Chunks) => {
  return request.get<number[]>(`/files/checkChunks`, { params: chunks })
}
// 合并分片
export const mergeChunks = (chunkInfo: ChunkInfo) => {
  return request.post<string>(`/files/merge`, chunkInfo, { showMessage: true })
}

// 删除文件
export const deleteFile = (fileInfo: fileInfo) => {
  const url =
    fileInfo.fileType === 'folder'
      ? `/folders/${fileInfo.id}`
      : `/files/${fileInfo.id}`
  return request.delete<string>(url, { showMessage: true })
}
// 添加文件夹
export const addFolder = (folderInfo: AddFolder) => {
  return request.post<string>(`/folders`, folderInfo, { showMessage: true })
}
// 获取文件夹
export const getFolders = (folderData: FileInfo) => {
  return request.get<fileInfo[]>(`/folders`, {
    params: folderData
  })
}
// 更新folderId
export const updateFolderId = (folderInfo: UpdateFolderId) => {
  return request.post(`/files/uploadFolderId`, folderInfo, {
    showMessage: true
  })
}
// export const getInfo = () => {
//   return request.get<UserInfo>('/user/userinfo/user')
// }

// export const sendReisterCode = () => {
//   return request.get('/sendReisterCode')
// }
